package com.example.accessibilitydemo.autoclick3

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.content.Context
import android.content.Intent
import android.graphics.Path
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import androidx.annotation.RequiresApi

object AsUtils {


    /**
     * 查找节点信息
     *
     * @param id
     * @param text
     * @param contentDescription
     * @return null表示未找到
     */
    fun findNodeInfo(
        service: AccessibilityService,
        id: String,
        text: String,
        contentDescription: String
    ): AccessibilityNodeInfo? {
        if (TextUtils.isEmpty(text) && TextUtils.isEmpty(contentDescription)) {
            return null
        }
        val nodeInfo = service.rootInActiveWindow
        if (nodeInfo != null) {
            val list = nodeInfo.findAccessibilityNodeInfosByViewId(id)
            for (n in list) {
                val nodeInfoText =
                    if (TextUtils.isEmpty(n.text)) "" else n.text
                        .toString()
                val nodeContentDescription =
                    if (TextUtils.isEmpty(n.contentDescription)) "" else n.contentDescription
                        .toString()
                Log.e("aaa-->", "nodeInfoText-->${nodeInfoText}")
                Log.e("aaa1-->", "nodeContentDescription-->${nodeContentDescription}")
                if (TextUtils.isEmpty(text)) {
                    if (contentDescription == nodeContentDescription) {
                        return n
                    }
                } else {
                    if (text == nodeInfoText) {
                        return n
                    }
                }
            }
        } else {
            Log.e("abc", "")
        }
        return null
    }

    fun findNodeInfo2(
        service: AccessibilityService,
        id: String,
        text: String,
        contentDescription: String,
        callback: (AccessibilityNodeInfo?) -> Unit
    ) {
        if (TextUtils.isEmpty(text) && TextUtils.isEmpty(contentDescription)) {
            callback(null)
        }
        val handler = Handler(Looper.getMainLooper())
        handler.postDelayed({
            val nodeInfo = service.rootInActiveWindow
            if (nodeInfo != null) {
                val list = nodeInfo.findAccessibilityNodeInfosByViewId(id)
                for (n in list) {
                    val nodeInfoText =
                        if (TextUtils.isEmpty(n.text)) "" else n.text
                            .toString()
                    val nodeContentDescription =
                        if (TextUtils.isEmpty(n.contentDescription)) "" else n.contentDescription
                            .toString()
                    Log.e("aaa-->", "nodeInfoText-->${nodeInfoText}")
                    Log.e("aaa1-->", "nodeContentDescription-->${nodeContentDescription}")
                    if (TextUtils.isEmpty(text)) {
                        if (contentDescription == nodeContentDescription) {
                            callback(n)
                        }
                    } else {
                        if (text == nodeInfoText) {
                            callback(n)
                        }
                    }
                }
            } else {
                Log.e("abc", "")
                service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME)
                handler.postDelayed({

//                    launchApp("com.example.myapplication2", service.applicationContext)

                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS)


                }, 200)

            }
        }, 200)
    }

    /**
     * 点击节点
     * @return true表示点击成功
     */
    fun performClickNodeInfo(nodeInfo: AccessibilityNodeInfo?): Boolean {
//        if (nodeInfo != null) {
//            Log.e("bbb", "bbb")
//            if (nodeInfo.isClickable) {
//                Log.e("bbb1", "bbb")
//                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)
//                return true
//            } else {
//                val parent = nodeInfo.parent
//                if (parent != null) {
//                    Log.e("bbb2", "bbb")
//                    val isParentClickSuccess = performClickNodeInfo(parent)
//                    parent.recycle()
//                    return isParentClickSuccess
//                }
//                Log.e("bbb3", "bbb")
//            }
//        }


        val node = nodeInfo?.findAccessibilityNodeInfosByText("BT1")?.firstOrNull()
        if (node != null && node.isClickable) {
            var bool = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            if (!bool) {
                Log.e("aaa","aaaa111")
                performClickNodeInfo(nodeInfo)
            }
        }

        return false
    }


    /**
     * 坐标模拟点击:最低api24，即要求Android7.0以上
     */
    @RequiresApi(Build.VERSION_CODES.N)
    fun click(accessibilityService: AccessibilityService, x: Float, y: Float) {
        val builder = GestureDescription.Builder()
        val path = Path()
        path.moveTo(x, y)
        path.lineTo(x, y)
        builder.addStroke(GestureDescription.StrokeDescription(path, 0, 1))
        val gesture = builder.build()
        accessibilityService.dispatchGesture(
            gesture,
            object : AccessibilityService.GestureResultCallback() {
                override fun onCancelled(gestureDescription: GestureDescription) {
                    super.onCancelled(gestureDescription)
                }

                override fun onCompleted(gestureDescription: GestureDescription) {
                    super.onCompleted(gestureDescription)
                }
            },
            null
        )
    }


    fun launchApp(packageName: String, ctx: Context) {
        val context = ctx
        val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName)
        if (launchIntent != null) {
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(launchIntent)
        } else {
            // 处理未找到应用的情况
        }
    }

}